<?php
namespace src;
use classlib\input;
use src\logic\ltags;
use src\logic\limapi;
use src\logic\lrobots;
use src\logic\Cadmin;
use classlib\core as C;
use classlib\core\controller;
class Cstudio extends controller {
	public function main() {
		$view  = C\view::inst('extjs');
		Cadmin::chkaccess($view);
		$lang  = C\lang::inst('adm');
		$dlang = C\lang::inst('dd');
		$area  = \src\logic\lconfig::dd('system_rtmp_area');
		$view->assign('area', $area);
		$view->assign('status', $dlang->get('sh0006'));
		$view->assign('yes2no', $dlang->get('sh0007'));
		$view->assign_by_ref('title', Cadmin::$name);
		$view->display('live/studio.ext.js');
	}
	
	/**
	 * @desc    手动推荐/置顶/热门直播间资料信息
	 * @doc     手动推荐/置顶/热门
	 * @access  需要授权 
	 */
	public function dosets() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$field  = input::get_post('field');
		$field  = trim($field);
		$sfields= array('isrecommend', 'istop', 'ishot', 'iscurated');
		if (in_array($field, $sfields)) {//非自定义字段不允许修改
			$ids    = \classlib\validator\auditor::intstr2arr('ids');
			$fields = array($field=>0);
			$orm    = C\model::load('pro.pl.studio');
			foreach ($ids as $id) {
				$studio = $orm->get_one($id);
				if (!$studio) {
					continue;
				}
				$fields[$field] = ($studio[$field] == 0)? 1:0;
				if ($field == 'isrecommend' && $fields[$field] == 1) {
					$fields[$field] = C\config::$nowtime;
				}
				$orm->save($id, $fields);
			}
			Cadmin::log2db('studio_dosets:'.implode(',', $ids).C\view::inst('xml')->array2xml($fields));
		}
		$view->display();
	}
	
	/**
	 * @desc    禁用或者解禁直播间的状态信息
	 * @doc     设置状态
	 * @access  需要授权
	 */
	public function dostatus() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$ids    = \classlib\validator\auditor::intstr2arr('ids');
		$status = (int)input::get_post('status');
		$status = ($status != 1)? 0:1;
		$attachs= '';
		$msg    = '';
		$remark = input::get_post('remark');
		//遍历直播间的信息
		$field  = array('status'=>$status, 'olstatus'=>0, 'oltools'=>'admreject');
		if ($status == 0) {
			$dlang  = C\lang::inst('dd');
			$reason = $dlang->get('log0002');
			$remark = isset($reason[$remark])? $reason[$remark]:$reason[1];
			$acl    = \classlib\acl::inst();
			$res    = \src\logic\upfile::inst($acl)->post('Filedata');
			if ($res) {
				$attachs = $res['url'];
			}
			//设置锁定的时间 到期时间
			$duration = (int)input::get_post('duration');
			$expire   = ($duration == -1)? -1:(($duration * 3600)+C\config::$nowtime);
			$field['expire'] = $expire;
			//设置消息提醒
			$lang     = C\lang::inst('web');
			$dddurats = $dlang->get('log0003');
			if ($duration == -1) {
				unset($field['status']);
				$msg  = $lang->get('action', '80142');
			} else {
				$msg  = $lang->txt('action', '80143', $reason, $dddurats[$duration]);
			}
		}
		$orm    = C\model::load('pro.pl.studio');
		$xmlstr = C\view::inst('xml')->array2xml($field);
		foreach ($ids as $sid) {
			$studio = $orm->get_one($sid);
			if (!$studio || $studio['status'] == $status) {
				continue;
			}
			//禁播的时候且当前是在直播状态发送消息广播
			if ($studio['olstatus'] != 0 && $status == 0) {
				limapi::notifystatus($sid, $studio['userid'], $studio['rtocken'], 0, 0);
			}
			//这里逻辑有bug 禁播逻辑
			if ($status == 0 && $msg) {
				limapi::notifystudio($sid, json_encode(array('msg'=>$msg)), 0, 20014);
			}
			$ldata = array('sid'=>$sid, 'status'=>$status, 'remark'=>$remark, 'msg'=>$msg, 'field'=>$xmlstr);
			Cadmin::log2db('studio_dostatus:'.C\view::inst('xml')->array2xml($ldata));
			$orm->save($sid, $field);
			lrobots::reset($sid);
		}	
		$view->display();
	}
	
	/**
	 * @desc    新增以及编辑直播间资料信息
	 * @doc     编辑资料
	 * @access  需要授权 
	 */
	public function dosave() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$data   = array('stime'=>C\config::$nowtime);
		$filter = new \classlib\validator\auditor();
		$lang   = C\lang::inst('adm');
		$filter->lang($lang);
		$id     = (int)input::get_post('id');
		try {
			$data['title']    = $filter->reset('title')->lbetween(1, 255)->run();
			$data['studiono'] = $filter->reset('studiono')->alphanum()->lbetween(1, 15)->run();
			$data['tagids']   = $filter->reset('tagids')->numeric()->min(1)->run();
			$data['iscurated']= $filter->reset('iscurated')->numeric()->between(0, 1)->run();
			$data['iscasual'] = $filter->reset('iscasual')->numeric()->between(0, 1)->run();
			$data['testing']  = $filter->reset('testing')->numeric()->between(0, 1)->run();
			$data['isdoubt']  = $filter->reset('isdoubt')->numeric()->between(0, 1)->run();
			$acl = \classlib\acl::inst();
			$res = \src\logic\upfile::inst($acl)->post('Filedata');
			if ($res) {
				$data['thumb']= $res['url'];
			}
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$forwards  		  	  = \classlib\validator\auditor::intstr2arr('def_forward');
		$data['def_forward']  = (int)array_sum($forwards);
		//验证地址是否存在
		$orm    = C\model::load('pro.pl.studio');
		$studio = $orm->get_item(array('studiono'=>$data['studiono']));
		if ($id < 1 || ($studio && $studio['id'] != $id)) {
			$view->assign_error('studiono', $lang->common(40002));
		}
		//更新昵称和Domain信息 保存信息
		$studio = $orm->get_one($id);
		if (!$studio || $studio['userid'] < 1) {
			$view->assign_error('studiono', $lang->common(40002));
		}
		$user   = C\model::load('pro.pl.userinfo')->get_one($studio['userid']);
		$data['author'] = $user['nickname'];
		$orm->save($id, $data);
		//记录Tag关系
		if ($data['tagids'] != $studio['tagids']) {
			$ltagids = array($data['tagids']);
			\src\logic\ltags::build($id, $ltagids);
		}
		Cadmin::log2db('studio_save:'.$id.C\view::inst('xml')->array2xml($data));
		$view->display();
	}
	
	/**
	 * 获取用户资料列表
	 */
	public function dolist() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		list($start, $limit, $sort) = Cadmin::offset();
		$where  = array();
		$query  = input::get_post('query');
		$query  = trim($query);
		if ($query && !empty($query)) {
			$where[] = array('(');
			$where[] = array('title', '%'.$query.'%', \classlib\orm::OP_LIKE);
			$where[] = array('author', '%'.$query.'%', \classlib\orm::OP_LIKE, \classlib\orm::OP_OR);
			$where[] = array(')');
		}
		$userid = input::get_post('userid');
		if (is_numeric($userid) && $userid > 0) {
			$where['userid'] = $userid;
		}
		$studiono= input::get_post('studiono');
		$studiono= trim($studiono);
		if($studiono && !empty($studiono)) {
			$where['studiono'] = $studiono;
		}
		$olstatus = input::get_post('olstatus');
		if (is_numeric($olstatus)) {
			$where['olstatus'] = $olstatus;
		}
		$status = input::get_post('status');
		if (is_numeric($status)) {
			$where['status'] = $status;
		}
		$tagids = input::get_post('tagids');
		if (is_numeric($tagids)) {
			$where['tagids'] = $tagids;
		}
		$starlv = input::get_post('starlv');
		if (is_numeric($starlv)) {
			$table   = C\model::load('pro.pl.anchor')->get_table();
			$sql = sprintf('(select userid from %d where starlv=%d)', $table, $starlv);
			$where[] = array('userid', $sql, \classlib\orm::OP_IN, \classlib\orm::OP_SQL);
		}
		$orm    = C\model::load('pro.pl.studio');
		$total  = $orm->get_total($where);
		$list   = array();
		
		if ($total) {
			$list   = $orm->get_list($start, $limit, $where, '*', $sort);
			$sorm   = C\model::load('pro.inc.star');
			$aorm   = C\model::load('pro.pl.anchor');
			$area   = \src\logic\lconfig::dd('system_rtmp_area');
			foreach ($list as &$item) {
				$anchor = $aorm->get_one($item['userid']);
				$star   = $sorm->get_one($anchor['starlv']);
				$item['author']   = Cadmin::user($item['userid']);
				$item['starlv']   = empty($star)? '':$star['name'].'['.$star['star'].']';
				$item['airtime']  = ($item['airtime'] > C\config::$nowtime)? date('Y-m-d H:i', $item['airtime']):'';
				$item['lasttime'] = ($item['lasttime'] > 0)? date('Y-m-d H:i', $item['lasttime']):'';
				$item['jointime'] = date('Y-m-d H:i', $item['jointime']);
				$item['stime']    = date('Y-m-d H:i', $item['stime']);
				$item['tags']     = ltags::stag_name($item['tagids']);
				$item['link']     = C\router::get_url('live', $item['studiono']);
				$item['regname']  = isset($area[$item['region']])? $area[$item['region']]:'Unknow';
				$item['record']   = C\router::get_url('admin/live/basic/event', 'main', array('userid'=>$item['userid']));
				self::get_forward_area($item, $area);
			}
		}
		$view->assign_by_ref('total', $total);
		$view->assign_by_ref('dataset', $list);
		$view->display();
	}
	
	//获取Forward配置信息
	public static function get_forward_area(&$item, &$area) {
		$bforward = $bforwardids = $aforward = $aforwardids = array();
		$item['forward'] 	 = intval($item['forward']);
		$item['def_forward'] = intval($item['def_forward']);
		foreach ($area as $idx=>$name) {
			$idx = intval($idx);
			if ($item['forward'] & $idx) {
				$aforward[]    = $name;
				$aforwardids[] = $idx;
			}
			if ($item['def_forward'] & $idx) {
				$bforward[]    = $name;
				$bforwardids[] = $idx;
			}
		}
		$item['nowforwardname'] = implode(',', $aforward);
		$item['nowforwardids']  = implode(',', $aforwardids);
		$item['defforwardname'] = implode(',', $bforward);
		$item['defforwardids']  = implode(',', $bforwardids);
	}
}